$(document).ready(function() {
	var userId = $("#hidden_userId").val();
	//$("#zTreeDemoBackground").css({"width":"228px"});
	if (!StrUtil.isEmpty(userId)){
		//修改用户信息的处理
		//$().val("");
		$("#reset_btn").css({"display":"none"});
		getUser(userId);
	}else{
		$("#organization").hide();
	}
	//新增用户时，如果当前用户已是物业用户，则新增的用户的所属物业公司应该与当前用户一致，如果是修改用户，则已以用户的属性物业公司为准
	var ownerCompanyId = $("#property_company_name").attr("data-oid");
	if (!StrUtil.isEmpty(ownerCompanyId)){
		var currCompanyId= $("#property_company_name").attr("data-id");
		if (!StrUtil.isEmpty(userId) && !StrUtil.isEmpty(currCompanyId)){
			
		}else{
			$("#property_company_name").attr("data-id",$("#property_company_name").attr("data-oid"));
			$("#property_company_name").val($("#property_company_name").attr("data-oname"));
		}

		$("#property_company_name").attr("readonly",true);//不可更改
	}
	
	$("#submit_btn").bind("click",saveUser);
	$("#user_type").change(function() {
		var userTypeValue = $(this).val();
		if (userTypeValue == "11") {
			$("#organization").show();
		} else {
			$("#organization").hide();
		}
	});
	$("#search-type").change(function() {
		var st = $(this).val();
		if (st == "wuyegongsi") {
			$("#property_company_name").css({"display":"inline"});
			$("#n-keyword-input").css({"display":"none"});
		} else {
			$("#property_company_name").css({"display":"none"});
			$("#n-keyword-input").css({"display":"inline"});
		}
	});
	$("#property_company_name").autocomplete({
        source:function(request,response){
           $.ajax({
               type:"POST",
               url:"communityAction!getCompany.action",
               dataType:"json",
               data : {
                   "inParma": JSON.stringify({"companyName":request.term,"qryType":"getCompanySimple"})
               },
               success: function(data) {
            	   data = eval("("+data+")").data;

                   response($.map(data, function(item) {
                       return { label: item.companyName+"（"+item.regionWithSHQ+"）", value: item.companyName ,companyId:item.companyId}
                   }
                   
                   ));
               }
           });
       },
       delay:500,
       select: function(event, ui){
    	   $("#property_company_name").attr("data-id",ui.item.companyId);
    	   initTree();
       },
       change: function( event, ui ) {
    	   if (ui.item == null || ui.item == "null" || typeof(ui.item) == "undefined"){
    		   $("#property_company_name").attr("data-id",null);
    		   $("#property_company_name").val("");
    	   }
       }
   });
	/*var company = new CompanyObj("#property_company_name");
	company.complete();
	$("#property_company_name").change(function(){
		//改变物业公司时要重新加载小区单位树
		initTree();
	});*/
	initTree();
	getRoles(userId);
});
var treeNodes; 
function initTree() {
	var companyId = $("#property_company_name").attr("data-id");
	$.ajax({  
        async : false,  
        cache:false,  
        type: 'POST', 
        data: {comingParams:JSON.stringify({"companyId" :companyId,"userId":$("#hidden_userId").val()})},
        dataType : "json",  
        url: "userAction!getOrgs.action",//请求的action路径  
        error: function () {//请求失败处理函数  
            alert('请求失败');  
        },  
        success:function(data){ //请求成功后处理函数。    
        	data = eval("(" + data + ")");
            treeNodes = data.data;   //把后台封装好的简单Json格式赋给treeNodes  
        }  
    });
	var zTreeDemo = $.fn.zTree.init($("#cityTree"),setting, treeNodes);
	var nodes = zTreeDemo.getNodes();
	/*disabled = true, inheritParent = true, inheritChildren = false;
	for (var i = 0; i<nodes.length; i++) {
		zTreeDemo.setChkDisabled(nodes[i], disabled, inheritParent, inheritChildren);
	}*/
}

var setting = {
	check: {
		enable: true,
		chkStyle: "checkbox",
		chkboxType: {"Y":"","N":""}
	},
	data: {
		simpleData: {
			enable: true
		}
	}
};
function getUser(userId){
	$.ajax({  
        async : false,  
        cache:false,  
        type: 'POST', 
        data: {"comingParams" : JSON.stringify({"userId" :userId})},
        dataType : "json",  
        url: "userAction!getUser.action",//请求的action路径  
        error: function () {//请求失败处理函数  
            alert('请求失败');  
        },  
        success:function(data){ //请求成功后处理函数。    
        	data = eval("("+data+")");
	    	if (data.result == "true") {
	    		des(data);
			}else {
				alert("查询失败"+data.msg);
			}
        }  
    });
	/*$.post(
		    "userAction!getUser.action",
		    {"comingParams" : JSON.stringify({"userId" :userId})},
		    function(data) {
		    	data = eval("("+data+")");
		    	if (data.result == "true") {
		    		des(data);
				}else {
					alert("查询失败"+data.msg);
				}
		    	
		    }
		);*/
}
function getRoles(userId){
	
	$.ajax({  
        async : false,  
        cache:false,  
        type: 'POST', 
        data: {"comingParams" : JSON.stringify({"userId" :StrUtil.strnull(userId)})},
        dataType : "json",  
        url: "userAction!getRoles.action",//请求的action路径  
        error: function () {//请求失败处理函数  
            alert('请求失败');  
        },  
        success:function(data){ //请求成功后处理函数。    
        	data = eval("("+data+")");
	    	if (data.result == "true") {
	    		$(data.data).each(function(ix, ite) {
	    			var roleLabel = '<label class="checkbox inline"><input type="checkbox" value="'
	    				+ite.id+'" name="check"';
	    			if (ite.checked==true){ 
	    				roleLabel =roleLabel+'checked="checked"';
	    			}
	    			roleLabel = roleLabel + '/>'+ite.name+'</label>';
	    			$("#roles").append(roleLabel);
	    		});
			}else {
				alert("查询失败"+data.msg);
			}
        }  
    });
}
function des(data){
	var dataList = data.data;
	if (dataList != null) {
		var user = dataList[0];
		$("#user_account").val(user.account);
		var partyInfo = user.partyInfo;
		if (!StrUtil.isEmpty(partyInfo)){
			$("#user_name").val(partyInfo.partyName);
			$("#user_name").attr("data-id",partyInfo.partyInfoId);
			$("#user_qq").val(partyInfo.qq);
			$("#user_email").val(partyInfo.email);
			$("#user_weixin").val(partyInfo.wx);
			
			var address = partyInfo.address;
			if (address != null){
				var area = address.area;
				var upArea1 = area.upArea;
				var upArea2 = upArea1.upArea;
				var detailAdd =address.detailAddress;

				editGetProvince(upArea2.areaId);
				editGetCity(upArea2.areaId,upArea1.areaId);
				editGetArea(upArea1.areaId,area.areaId);
				$("#user_address").val(detailAdd);
				$("#user_cert_type option[value='"+partyInfo.certType+"']").attr("selected",true);
				$("#user_cert_nbr").val(partyInfo.certNbr);
			}
			
			
		}
		if ('10' == user.userType){
			$("#organization").hide();
		}
		
		$("#user_type option[value='"+user.userType+"']").attr("selected",true);
		
		$("#user_status option[value='"+user.statusCd+"']").attr("selected",true);
		
		if (!StrUtil.isEmpty(user.company)){
			$("#property_company_name").val(user.company.companyName);
			$("#property_company_name").attr("data-id",user.company.companyId);
		}
		if (!StrUtil.isEmpty(user.community)){
			$("#community_name").val(user.community.communityName);
			$("#community_name").attr("data-id",user.community.communityId);
		}
	}
}


function saveUser() {
	var user_account = $("input[name='user_account']").val();		//帐号（手机号）
	if (user_account == "") {
		$.sucmodal("提示", "帐号（手机号）必填");
		return;
	}
	var reg = /^(13[0-9]|14[0-9]|15[0-9]|18[0-9])\d{8}$/i;
	if(!reg.test(user_account))
	{
  		$.sucmodal("提示", "手机号格式不正确！");
  		return;
	}
	var user_name = $("input[name='user_name']").val();		//姓名
	if (user_name == "") {
		$.sucmodal("提示", "用户姓名必填");
		return;
	}
	var user_cert_type = $("#user_cert_type option:selected").val();		//证件类型
	var user_cert_nbr = $("input[name='user_cert_nbr']").val();		//证件号码
	var user_status = $("#user_status option:selected").val();		//用户状态
	var user_type = $("#user_type option:selected").val();			//用户类型
	if (user_type == "") {
		$.sucmodal("提示", "用户类型必填必填");
		return;
	}
	
	if(user_cert_type =='10') { //证件类型是身份证时要验证下身份证号码是否符合格式
		var reg2 = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
		if(!reg2.test(user_cert_nbr))  {  
       		$.sucmodal("提示","身份证输入不合法");  
       		return;  
   		}  
	}
	
	var user_qq = $("input[name='user_qq']").val();		//QQ
	var user_email = $("input[name='user_email']").val();		//email
	var user_wx = $("input[name='user_wx']").val();		//微信
	/*var area_area = $("#area_area option:selected").val();		//地区
	if (area_area == "") {
		$.sucmodal("提示", "地区必填");
		return;
	}
	var user_address = $("input[name='user_address']").val();		//详情地址
	if (user_address == "") {
		$.sucmodal("提示", "详情地址必填");
		return;
	}*/
	var user_address = $("input[name='user_address']").val();		//详情地址
	var user_company_id = $("#property_company_name").attr("data-id");		//物业公司
	if (user_type == "11") {
		if (StrUtil.isEmpty(user_company_id)){
			$.sucmodal("提示", "系统类型是物业用户，物业公司必填");
			return;
		}
	}

	var jsarray = new Array();
	var user = {
			propertyCompany : {},
			partyInfo : {
				address : {
					area : {}
				}
			},
			userOrgRel :{},
			userAuth:{}
	};
	var inparam = {data:{}};
	
	//单位信息
	var zTree = $.fn.zTree.getZTreeObj("cityTree");
	var pri = zTree.getCheckedNodes(true);
	if (pri.length >0) {
		var orgArray = new Array();
		for(i=0;i<pri.length;i++) {
			var userOrgRel = {};
			userOrgRel.orgId = pri[i].id;
			orgArray.push(userOrgRel);
		}
		user.userOrgRel = orgArray;
	}else {
		if (user_type == "11") {
			//物业用户必须选至少一个单位
			$.sucmodal("提示", "物业用户必须选择至少一个单位");
			return;
		}
	}
	//var user_community_id = $("#community_name").attr("data-id");	//单位信息
	var chk_value =[]; 
	$('input[name="check"]:checked').each(function(){ 
		var userAuth = {};
		userAuth.roleId=$(this).val();
		chk_value.push(userAuth); 
	});
	
	var userId = $("#hidden_userId").val();
	if (!StrUtil.isEmpty(userId)){
		user.userId = userId;
	}
	user.account = user_account;		//帐号
	user.statusCd = user_status;		//状态
	user.userType = user_type;		//用户类型
	//jsondata.area.areaId = area_area;			//地区
	user.partyInfo.partyName = user_name;	//姓名
	user.partyInfo.address.detailAddress=user_address;
	if (user_cert_type != '0'){
		partyInfo.certType = user_cert_type;	//证件类型
		partyInfo.certNbr = user_cert_nbr;	//证件号码
	}
	
	user.partyInfo.weiXin=user_wx;		//微信
	user.partyInfo.email=user_email;			//email
	user.partyInfo.qq=user_qq;				//qq
	//jsondata.address.detailAddress = user_address;  //详情地址
	user.propertyCompany.companyId = user_company_id;	//物业公司
	//jsondata.community.communityId = user_community_id;		//小区
	user.userAuth = chk_value;						//角色
	jsarray.push(user);
	inparam.data=jsarray;
	$.post("userAction!saveUser.action",{
		comingParams : JSON.stringify(inparam)
	},function(data) {
		data = eval("(" + data + ")");
		if (data.result == "true") {
			$.sucmodal("提示", data.msg, function() {
				location.href = "userManager.jsp";
			});
		} else {
			alert("保存失败" + data.msg);
		}
	});
}